package com.hsgene.consumables.service.impl;

import com.hsgene.common.util.basic.UUID32;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.support.PeanutPagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.consumables.condition.ApplyCondition;
import com.hsgene.consumables.constant.ConsumablesApplyStatus;
import com.hsgene.consumables.constant.GoodsApplyStatus;
import com.hsgene.consumables.domain.*;
import com.hsgene.consumables.domain.v1.GeneticGoods;
import com.hsgene.consumables.domain.v1.GeneticGoodsApplyHistory;
import com.hsgene.consumables.dto.*;
import com.hsgene.consumables.dto.peanut.*;
import com.hsgene.consumables.persistence.ConsumablesApplyRepository;
import com.hsgene.consumables.persistence.GoodsRepository;
import com.hsgene.consumables.service.ConsumablesApplyService;
import com.hsgene.consumables.service.api.*;
import com.hsgene.dict.dto.SysDictDto;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.logistics.domain.LogisticsInfo;
import com.hsgene.user.dto.user.employee.EmployeeDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 耗材申请、发送、寄送service
 *
 * @author wxf
 * @date 2018/8/20 11:09
 **/
@Service
public class ConsumablesApplyServiceImpl implements ConsumablesApplyService {

    @Resource
    private ConsumablesApplyRepository applyRepository;

    @Resource
    private GeneratorService generatorService;

    @Resource
    private UserService userService;

    @Resource
    private LogisticsService logisticsService;

    @Resource
    private DictService dictService;

    @Resource
    private GoodsRepository goodsRepository;

    /**
     * 申请耗材信息
     *
     * @param applyInfos 耗材信息
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public String addConsumablesApplyInfo(ConsumablesApplyInfoDto applyInfos) {
        List<ConsumablesApplyDetailInfo> applyDetailInfoList = new ArrayList<>();
        //获取genetic_goods_apply
        ConsumablesApplyInfo applyInfo = getBasicApplyInfo(applyInfos);
        for (ConsumablesApplyDetailsInfoDto applyInfoDto : applyInfos.getApplyDetailsInfoDtoList()) {
            //获取genetic_goods_apply_detail
            ConsumablesApplyDetailInfo applyDetailInfo = getApplyDetailInfo(applyInfoDto, applyInfo);
            applyDetailInfoList.add(applyDetailInfo);
        }
        //增加一条申请记录
        applyRepository.addConsumablesApplyInfo(applyInfo);
        //申请详情
        applyRepository.addConsumablesApplyDetailsInfo(applyDetailInfoList);
        return applyInfo.getApplyNo();
    }

    /**
     * 更新状态
     *
     * @param shipInfo 发放信息
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public boolean updateConsumablesApplyInfo(ConsumablesApplyShipInfo shipInfo) {
        //获取发放人信息
        ApiResult<EmployeeDto> userInfo = userService.findEmployee(shipInfo.getProvideId());
        String provideName = "未知";
        if (userInfo.isSucc()) {
            provideName = userInfo.getData().getNickName();
        }
        return applyRepository.updateConsumablesApplyInfo(shipInfo, provideName);
    }

    /**
     * 寄送
     *
     * @param expressInfoDto 寄送信息
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public boolean sendConsumablesApply(ConsumablesExpressInfoDto expressInfoDto) {
        //寄送的物流信息存入geneshop_logistics_info表
        LogisticsInfo logisticsInfo = getLogisticsInfo(expressInfoDto);
        //logisticsService.addLogistics(logisticsInfo);
        return applyRepository.sendConsumablesApply(expressInfoDto);
    }

    private LogisticsInfo getLogisticsInfo(ConsumablesExpressInfoDto expressInfoDto) {
        LogisticsInfo logisticsInfo = new LogisticsInfo();
        logisticsInfo.setExpressCompany(expressInfoDto.getExpress());
        logisticsInfo.setExpressNumber(expressInfoDto.getExpressNo());
        logisticsInfo.setOrderId(expressInfoDto.getApplyNo());
        logisticsInfo.setConfirmPersonAddress(expressInfoDto.getRecipientsAddress());
        logisticsInfo.setConfirmPersonPhone(expressInfoDto.getRecipientsPhone());
        // logisticsInfo.setCreateBy(expressInfoDto.getCreateBy());
        // logisticsInfo.setCreateTime(expressInfoDto.getCreateDate());
        return logisticsInfo;
    }

    /**
     * 查看申请详情
     *
     * @param applyNo 申请编号
     * @return
     */
    @Override
    public Object getConsumablesApplyDetailsInfo(String applyNo) {
        Object object = applyRepository.getConsumablesApplyDetailsInfo(applyNo);
        if (object instanceof ConsumablesApplyProvideInfo) {
            ConsumablesApplyProvideInfo provideInfo = (ConsumablesApplyProvideInfo) object;
            provideInfo.setStatusDesc(ConsumablesApplyStatus.getEnum(provideInfo.getStatus()).getDesc());
            return provideInfo;
        } else if (object instanceof ConsumablesExpressInfoDto) {
            ConsumablesExpressInfoDto expressInfoDto = (ConsumablesExpressInfoDto) object;
            expressInfoDto.setStatusDesc(ConsumablesApplyStatus.getEnum(expressInfoDto.getStatus()).getDesc());
            return expressInfoDto;
        }
        return object;
    }

    /**
     * 签收
     *
     * @param applyNo 单号
     * @param date    时间
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public boolean receiptConsumablesInfo(String applyNo, Date date) {
        return applyRepository.receiptConsumablesInfo(applyNo, date);
    }

    /**
     * 查询物流
     *
     * @param applyNo 申请编号
     * @return
     */
    @Override
    public ApiResult<List<LogisticsInfo>> queryExpressInfo(String applyNo) {
        return logisticsService.queryLogistics(applyNo);
    }

    /**
     * 查询列表
     *
     * @param condition 条件
     * @return
     */
    @Override
    public List<ConsumablesListInfoDto> queryConsumblesList(ConsumablesQueryCondition condition) {
        //校验page
        if (condition.getPage() <= 0) {
            condition.setPage(1);
        }
        List<ConsumablesListInfoDto> result = applyRepository.queryConsumblesList(condition, (condition.getPage() - 1) *
                10, 10);
        if (result == null || result.isEmpty()) {
            return new ArrayList<>();
        }
        result.stream().forEach(infoDto -> {
            infoDto.setStatusDesc(ConsumablesApplyStatus.getEnum(infoDto.getStatus()).getDesc());
        });
        return result;
    }

    /**
     * 耗材审核列表
     *
     * @param applyCondition 查询条件
     * @return
     */
    @Override
    public ApiResult queryApplys(ApplyCondition applyCondition) {
        FieldChecker.checkEmpty(applyCondition.getLimitHelper(), "分页条件");
        //如果没有指定排序规则，就按照申领时间降序排序
        if (StringUtils.isEmpty(applyCondition.getTimeSort()) && StringUtils.isEmpty(applyCondition.getStatusSort())) {
            applyCondition.setTimeSort("desc");
        }
        List<Integer> counts = applyRepository.queryApplyCount(applyCondition);
        int count = 0;
        if (counts != null) {
            count = counts.size();
        }
        Pagination<ConsumablesApplyDto> pagination = Pagination.newInstance(applyCondition.getLimitHelper(), count);
        List<ConsumablesApplyDto> applyPageDtos = new ArrayList<>();
        if (counts != null && counts.size() > 0) {
            applyPageDtos = applyRepository.queryApplys(applyCondition);
            if (applyPageDtos != null && applyPageDtos.size() > 0) {
                int rowNum = (applyCondition.getLimitHelper().getPage() - 1) * applyCondition.getLimitHelper().getSize();
                for (int i = 0; i < applyPageDtos.size(); i++) {
                    ConsumablesApplyDto consumablesApplyPageDto = applyPageDtos.get(i);
                    consumablesApplyPageDto.setNumber(rowNum + i + 1);
                    //耗材申领状态转换
                    consumablesApplyPageDto.setStatusDesc(GoodsApplyStatus.getEnum(consumablesApplyPageDto.getStatus()).getDesc());
                }
            }
        }
        pagination.setResult(applyPageDtos);
        return new ApiResult(200, "success", "查询列表成功", pagination);
    }

    /**
     * 耗材审核寄送弹窗展示信息获取
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult applyBaseInfo(String id) {
        ConsumablesApplyDto consumablesApplyDto = applyRepository.queryApplyBaseInfo(id);
        if (consumablesApplyDto != null) {
            List<String> address = applyRepository.queryGroundServantAddress(consumablesApplyDto.getGroundServantId());
            consumablesApplyDto.setAddress(address);
            //快递信息获取
            ApiResult<List<SysDictDto>> kuaidi = dictService.getDictByType("2000");
            consumablesApplyDto.setSysDictDtos(kuaidi.getData());
        }
        return new ApiResult(200, "success", "获取信息成功", consumablesApplyDto);
    }

    /**
     * 耗材寄送信息录入
     *
     * @param consumablesSendSignInfoDto
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public ApiResult applySendSign(ConsumablesSendSignInfo consumablesSendSignInfoDto) {
        ConsumablesApplyDetailDto applyDetailDto = applyRepository.queryApplyDetail(consumablesSendSignInfoDto.getApplyNo());
        if (applyDetailDto != null && GoodsApplyStatus.WAIT_SEND.getStatus() != applyDetailDto.getStatus()) {
            return new ApiResult(5001, "failed", "非待寄送状态的数据不能进行寄送操作", null);
        }
        ConsumablesSendSignInfoDto consumablesSendSignInfo = applyRepository.queryApplySendSignInfo(consumablesSendSignInfoDto.getApplyNo());
        consumablesSendSignInfoDto.setSendDateTime(new Date());
        //处理签收人信息
        if (!StringUtils.isEmpty(consumablesSendSignInfoDto.getSignerAddress())) {
            String[] signerInfo = consumablesSendSignInfoDto.getSignerAddress().split(" ");
            if (signerInfo != null && signerInfo.length > 0) {
                if (signerInfo.length == 1) {
                    consumablesSendSignInfoDto.setSignerAddress(signerInfo[0]);
                } else if (signerInfo.length == 2) {
                    consumablesSendSignInfoDto.setSignerAddress(signerInfo[0]);
                    consumablesSendSignInfoDto.setSignerName(signerInfo[1]);
                } else if (signerInfo.length == 3) {
                    consumablesSendSignInfoDto.setSignerAddress(signerInfo[0]);
                    consumablesSendSignInfoDto.setSignerName(signerInfo[1]);
                    consumablesSendSignInfoDto.setSignerPhone(signerInfo[2]);
                }
            }
        }
        //如果存在寄送信息则做修改，否则做添加操作
        if (consumablesSendSignInfo != null) {
            applyRepository.updateSendSign(consumablesSendSignInfoDto);
        } else {
            consumablesSendSignInfoDto.setDeleteFlag(0);
            ApiResult<GeneratorDto> generate = generatorService.generate("default", null);
            consumablesSendSignInfoDto.setId(generate.getData().getSerialNumber());
            applyRepository.insertSendSign(consumablesSendSignInfoDto);
        }
        applyRepository.updateApplyStatus(consumablesSendSignInfoDto.getApplyNo(), 4, "status");
        return new ApiResult(200, "success", "耗材寄送信息录入成功", null);
    }

    /**
     * 耗材申请详情
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult queryApplyDetail(String id) {
        ConsumablesApplyDetailDto consumablesApplyDetailDto = applyRepository.queryApplyDetail(id);
        if (consumablesApplyDetailDto != null && (consumablesApplyDetailDto.getStatus() == 5 || consumablesApplyDetailDto.getStatus() == 4)) {
            ConsumablesSendSignInfoDto sendSignInfoDto = applyRepository.queryApplySendSignInfo(consumablesApplyDetailDto.getApplyNo());
            if (sendSignInfoDto != null && !StringUtils.isEmpty(sendSignInfoDto.getSignerAddress())) {
                String[] split = sendSignInfoDto.getSignerAddress().split(" ");
                sendSignInfoDto.setSignerAddress(split[0]);
            }
            consumablesApplyDetailDto.setConsumablesSendSignInfoDto(sendSignInfoDto);
        }
        if (consumablesApplyDetailDto != null) {
            //查询审核信息
            List<ConsumablesApplyAuditDto> applyAuditDtos = applyRepository.applyAuditInfo(consumablesApplyDetailDto.getApplyNo());
            if (applyAuditDtos != null) {
                applyAuditDtos.forEach(consumablesApplyAuditDto -> {
                    consumablesApplyAuditDto.setStatus("1".equals(consumablesApplyAuditDto.getStatus()) ? "通过" : "拒绝");
                });
                consumablesApplyDetailDto.setConsumablesApplyAuditDtos(applyAuditDtos);
            }
        }
        return new ApiResult(200, "success", "耗材申请详情获取成功", consumablesApplyDetailDto);
    }

    /**
     * 耗材申请详情明细列表
     *
     * @param id          耗材申请编号
     * @param limitHelper 分页条件
     * @return
     */
    @Override
    public ApiResult queryApplyDetailPage(String id, LimitHelper limitHelper) {
        FieldChecker.checkEmpty(limitHelper, "分页条件");
        int count = applyRepository.applyHistoryCount(id);
        Pagination<ConsumablesApplyHistoryDto> pagination = Pagination.newInstance(limitHelper, count);
        List<ConsumablesApplyHistoryDto> applyHistoryDtos = new ArrayList<>();
        if (count > 0) {
            applyHistoryDtos = applyRepository.queryApplyHistorys(id, limitHelper);
            if (applyHistoryDtos != null && applyHistoryDtos.size() > 0) {
                int rowNum = (limitHelper.getPage() - 1) * limitHelper.getSize();
                for (int i = 0; i < applyHistoryDtos.size(); i++) {
                    ConsumablesApplyHistoryDto applyHistoryDto = applyHistoryDtos.get(i);
                    applyHistoryDto.setNumber(rowNum + i + 1);
                    //查询总的使用量
                    Integer userdTotal = applyRepository.userdTotal(applyHistoryDto.getGroundServantId(), applyHistoryDto.getGoodsId());
                    applyHistoryDto.setTotalUsedAmount(userdTotal==null?0:userdTotal);
                }
            }
        }
        pagination.setResult(applyHistoryDtos);
        return new ApiResult(200, "success", "订单明细查询成功", pagination);
    }

    /**
     * 审核申请
     *
     * @param consumablesApplyAudit
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public ApiResult auditStatus(ConsumablesApplyAudit consumablesApplyAudit) {
        //判断是否是待审批状态
        ConsumablesApplyDetailDto applyDetailDto = applyRepository.queryApplyDetail(consumablesApplyAudit.getApplyNo());
        if (applyDetailDto != null && GoodsApplyStatus.WAIT_AUDIT.getStatus() != applyDetailDto.getStatus()) {
            return new ApiResult(5001, "failed", "非待审批状态的数据不能进行此操作", null);
        }
        //修改耗材申请状态
        applyRepository.updateApplyStatus(consumablesApplyAudit.getApplyNo(), consumablesApplyAudit.getStatus(), "status");
        consumablesApplyAudit.setDeleteFlag(0);
        consumablesApplyAudit.setAuditDateTime(new Date());
        consumablesApplyAudit.setId(generatorService.generate("default", null).getData().getSerialNumber());
        if (consumablesApplyAudit.getStatus() == 3) {
            //若审核通过，需要更新此次申领的耗材的库存数量
            updateGoodsCount(consumablesApplyAudit.getApplyNo());
            consumablesApplyAudit.setStatus(1);
        } else {
            consumablesApplyAudit.setStatus(2);
        }
        applyRepository.insertApplyAudit(consumablesApplyAudit);
        return new ApiResult(200, "success", "审核成功", null);
    }

    /***
     * 耗材审核同意后，修改相关耗材的库存量
     * @author
     * @date 2018/10/25 14:51
     * @param applyNo 耗材申请编号
     * @return
     */
    public void updateGoodsCount(String applyNo) {
        List<Map<String, String>> goodsInfo = applyRepository.applyGoodsByNo(applyNo);
        for (Map<String, String> map : goodsInfo) {
            String goodsId = map.get("goodsId");
            GeneticGoods geneticGoods = goodsRepository.findById(goodsId);
            if (!StringUtils.isEmpty(map.get("applyAmount"))) {
                geneticGoods.setAmount(geneticGoods.getAmount() - Integer.parseInt(map.get("applyAmount")));
            }
            //更新耗材库存量
            goodsRepository.update(geneticGoods);
            //判断此地服是否申请过此耗材，如果没申请过则添加，如果申请过则修改
            Map<String, Integer> historyCount = applyRepository.applysHistoryCount(map.get("goodsId"), map.get("groundServantId"));
            if (historyCount == null) {
                GeneticGoodsApplyHistory applyHistory = new GeneticGoodsApplyHistory();
                ApiResult<GeneratorDto> generate = generatorService.generate("genetic_goods_apply_history", null);
                applyHistory.setId(generate.getData().getSerialNumber());
                applyHistory.setGoodsId(goodsId);
                applyHistory.setGroundServantId(map.get("groundServantId"));
                applyHistory.setTotalApplyAmount(StringUtils.isEmpty(map.get("applyAmount")) ? 0 : Integer.parseInt(map.get("applyAmount")));
                applyHistory.setLastUsedAmount(0);
                applyHistory.setTotalUsedAmount(0);
                applyHistory.setCreateDateTime(new Date());
                applyHistory.setUpdateDateTime(new Date());
                applyHistory.setDeleteFlag(false);
                applyRepository.insertApplyHistoryAmount(applyHistory);
            } else {
                applyRepository.updateTotalApplyAmount(map);
            }
        }
    }

    /**
     * 根据地服ID和关键字搜索已有耗材列表
     *
     * @param groundServantId 地服id
     * @param keyWords        关键字
     * @return
     */
    @Override
    public ApiResult groundServantGoods(String groundServantId, String keyWords) {
        List<GroundServantGoodsDto> groundServantGoods = applyRepository.groundServantGoods(groundServantId, keyWords);
        if (groundServantGoods != null && groundServantGoods.size() > 0) {
            groundServantGoods.forEach(groundServantGoodsDto -> {
                Map<String, Integer> historyCount = applyRepository.applysHistoryCount(groundServantGoodsDto.getGoodsId(), groundServantId);
                //计算当前地服的可使用量
                Integer totalApplyAmount = historyCount.get("totalApplyAmount");
                Integer totalUsedAmount = historyCount.get("totalUsedAmount");
                Integer currentNumber = null;
                if(totalApplyAmount != null && totalUsedAmount != null){
                    currentNumber = totalApplyAmount - totalUsedAmount;
                }else if(totalApplyAmount != null && totalUsedAmount == null){
                    currentNumber = totalApplyAmount;
                }
                groundServantGoodsDto.setCurrentNumber(currentNumber);
            });
        }
        return new ApiResult(200, "success", "数据获取成功", groundServantGoods);
    }

    /**
     * 花生仁耗材申领列表
     *
     * @param limitHelper 分页条件
     * @param listType    前端分类（申领状态）
     * @param orderBy     排序条件
     * @return
     */
    @Override
    public ApiResult peanutApplys(LimitHelper limitHelper, Integer listType, Integer orderBy) {
        FieldChecker.checkEmpty(limitHelper, "分页条件");
        //花生仁状态转换
        //listType=peanutApplyStatus(listType);
        List<Integer> counts = applyRepository.peanutApplyCount(listType);
        int count = 0;
        if (counts != null) {
            count = counts.size();
        }
        PeanutPagination<PeanutApplysDto> pagination = PeanutPagination.newInstance(limitHelper, count);
        List<PeanutApplysDto> peanutApplysDtos = new ArrayList<>();
        if (counts != null && counts.size() > 0) {
            String orderType = "create_date_time";
            if (orderBy != null && orderBy == 1) {
                orderType = "update_date_time";
            }
            peanutApplysDtos = applyRepository.peanutApplys(limitHelper, listType, orderType);
            if (peanutApplysDtos != null && peanutApplysDtos.size() > 0) {
                peanutApplysDtos.forEach(peanutApplysDto -> {
                    peanutApplysDto.setStatusDictLabel(GoodsApplyStatus.getEnum(peanutApplysDto.getStatus()).getDesc());
                });
            }
        }
        if (limitHelper.getPage() == pagination.getTotalPage()) {
            pagination.setLastPage(true);
        }
        pagination.setList(peanutApplysDtos);
        return new ApiResult(200, "success", "数据获取成功", pagination);
    }

    /**
     * 花生仁耗材申领详情
     *
     * @param id 申领id
     * @return
     */
    @Override
    public ApiResult peanutApplyDetail(String id) {
        //获取与此id同一批次的申领单id和申领单编号
        PeanutApplyIdDto applyIds = applyRepository.applyIds(id);
        String applyNo = applyIds.getApplyNo();
        //耗材申领信息查询
        PeanutApplyDetailDto peanutApplyDetailDto = applyRepository.peanutApplyDetail(applyNo);
        peanutApplyDetailDto.setId(id);
        peanutApplyDetailDto.setStatusDictLabel(GoodsApplyStatus.getEnum(peanutApplyDetailDto.getStatus()).getDesc());
        //获取耗材申领明细
        List<PeanutApplyHistoryDto> applyHistoryDtos = applyRepository.peanutApplyHistorys(applyIds.getApplyIds());
        peanutApplyDetailDto.setGoodsApplyDetailModelList(applyHistoryDtos);
        return new ApiResult(200, "success", "获取数据成功", peanutApplyDetailDto);
    }

    /**
     * 花生仁耗材申领签收
     *
     * @param id 耗材申领id
     * @return
     */
    @Override
    public ApiResult peanutSignIn(String id) {
        PeanutApplyIdDto applyIds = applyRepository.applyIds(id);
        applyRepository.updateApplyStatus(applyIds.getApplyNo(), 5, "status");
        applyRepository.updateApplySign(applyIds.getApplyNo(), new Date());
        return new ApiResult(200, "success", "签收成功", null);
    }

    /**
     * 花生仁取消耗材申领
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult peanutDelete(String id) {
        PeanutApplyIdDto applyIds = applyRepository.applyIds(id);
        applyRepository.updateApplyStatus(applyIds.getApplyNo(), 1, "delete_flag");
        return new ApiResult(200, "success", "取消成功", null);
    }

    private ConsumablesApplyInfo getBasicApplyInfo(ConsumablesApplyInfoDto applyInfoDto) {
        ConsumablesApplyInfo applyInfo = new ConsumablesApplyInfo();
        applyInfo.setApplyNo(getId());
        applyInfo.setId(UUID32.randomUUIDString());
        applyInfo.setCreateDate(applyInfoDto.getCreateTime());
        //获取地服人员信息
        addUserInfo(applyInfoDto.getUserId(), applyInfo);
        //状态(1：待审批 2：待修改 3：待发放 4：待寄送 5：待签收 6：已完成)
        applyInfo.setStatus(3);
        //0表示正常
        applyInfo.setDelFlag("0");
        return applyInfo;
    }

    private void addUserInfo(String userId, ConsumablesApplyInfo applyInfo) {
        ApiResult<EmployeeDto> userInfo = userService.findEmployee(userId);
        if (StringUtils.isEmpty(applyInfo.getCreateBy())) {
            applyInfo.setCreateBy(userId);
        }
        applyInfo.setUserId(userId);
        if (userInfo.isSucc()) {
            EmployeeDto employeeDto = userInfo.getData();
            applyInfo.setProvince(employeeDto.getConsignAddress().getProvinceName());
            applyInfo.setUserName(employeeDto.getNickName());
            applyInfo.setAddress(employeeDto.getConsignAddress().getAddress());
            applyInfo.setPhone(employeeDto.getPhone());
        }
    }

    private ConsumablesApplyDetailInfo getApplyDetailInfo(ConsumablesApplyDetailsInfoDto applyDetailsInfoDto,
                                                          ConsumablesApplyInfo applyInfo) {
        //获取累计申请量
        Integer accApplyNumber = applyRepository.getAccApplyNumber(applyInfo.getUserId(), applyDetailsInfoDto
                .getGooodsId());
        if (accApplyNumber == null) {
            accApplyNumber = 0;
        }
        ConsumablesApplyDetailInfo applyDetailInfo = new ConsumablesApplyDetailInfo();
        applyDetailInfo.setAccApplyNumber(accApplyNumber);
        applyDetailInfo.setApplyNumber(applyDetailsInfoDto.getApplyCount());
        applyDetailInfo.setApplyId(applyInfo.getId());
        applyDetailInfo.setId(UUID32.randomUUIDString());
        applyDetailInfo.setGoodsId(applyDetailsInfoDto.getGooodsId());
        applyDetailInfo.setGoodsName(applyDetailsInfoDto.getGooodsName());
        applyDetailInfo.setCreateDate(applyInfo.getCreateDate());
        applyDetailInfo.setDelFlag("0");
        applyDetailInfo.setCreateBy(applyInfo.getCreateBy());
        applyDetailInfo.setUserId(applyInfo.getUserId());
        return applyDetailInfo;
    }

    private String getId() {
        ApiResult<GeneratorDto> generatorResult = generatorService.generate("material_storage", null);
        if (generatorResult.isSucc()) {
            return generatorResult.getData().getSerialNumber();
        }
        return UUID32.randomUUIDString();
    }

    /**
     * 花生仁耗材申领单状态转换
     *
     * @param status 状态码
     * @return
     */
    public int peanutApplyStatus(int status) {
        if (status == 3) {
            status = 1;
        } else if (status == 4) {
            status = 3;
        } else if (status == 5) {
            status = 4;
        } else if (status == 6) {
            status = 5;
        }
        return status;
    }

    /**
     * 花生仁耗材申领单状态对应描述
     *
     * @param status 状态码
     * @return
     */
    public String peanutApplyStatusDesc(int status) {
        if (status == 1) {
            return "待审批";
        } else if (status == 2) {
            return "待修改";
        } else if (status == 3) {
            return "待发放";
        } else if (status == 4) {
            return "待寄送";
        } else if (status == 5) {
            return "待签收";
        } else if (status == 6) {
            return "已完成";
        }
        return null;
    }
}
